package com.ruoyi.tdqq.controller;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.system.api.RemoteDeptService;
import com.ruoyi.system.api.RemoteUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class TestController
{
    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private RemoteDeptService remoteDeptService;
    @Autowired
    private RestTemplate restTemplate;

    // 新增restTemplate对象注入方法，注意，此处LoadBalanced注解一定要加上，否则无法远程调用
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate()
    {
        return new RestTemplate();
    }

    @GetMapping("/user")
    public String get()
    {
        // 创建HttpHeaders对象并设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("source", SecurityConstants.INNER); // 示例：添加Authorization头
        //headers.set("Content-Type", "application/json"); // 示例：添加Content-Type头

        // 创建HttpEntity对象，封装请求头和（可选的）请求体
        HttpEntity<String> entity = new HttpEntity<>("body", headers); // 注意：对于GET请求，通常不需要请求体，所以也可以只传递headers

        // 使用exchange方法发送GET请求
        String url = "http://ruoyi-system/user/info/admin";
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

        // 获取响应体
        if (response.getStatusCode().is2xxSuccessful()) {
            String responseBody = response.getBody();
            System.out.println(responseBody);
        } else {
            System.out.println("Failed to get data");
        }
        return restTemplate.getForObject("http://ruoyi-system/user/info/admin?source={?}", String.class,"inner");
    }
    /**
     * 获取当前用户信息
     */
    @GetMapping("/user/{username}")
    public Object info(@PathVariable("username") String username)
    {
        return remoteUserService.getUserInfo(username, SecurityConstants.INNER);
    }

    @GetMapping("/dept/{deptId}")
    public Object getDeptChildrenList(@PathVariable("deptId") Long deptId)
    {
        return remoteDeptService.getDeptChildrenList(deptId, SecurityConstants.INNER);
    }
}